/*
 * 文件名称: App.java Copyright 2011-2016 Ximalaya All right reserved.
 */
package com.zxy.jdbcdemo;

import java.io.UnsupportedEncodingException;
import java.nio.charset.UnsupportedCharsetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.zip.CRC32;

/**
 * @author Bird Zhang
 */
public class QueryIbatorNode {

  public static TreeMap<Long, String> genNodes(String host, String user, String password, String dbName,
      String tbName) {

    TreeMap<Long, String> ret = new TreeMap<Long, String>();
    String jdbcUrl = "jdbc:mysql://" + host + ":3306/" + dbName + "?" + "user=" + user + "&password=" + password
        + "&useUnicode=true&characterEncoding=utf8";
    Statement statement = null;
    ResultSet resultSet = null;
    Connection conn = null;
    try {
      // 之所以要使用下面这条语句，是因为要使用MySQL的驱动，所以我们要把它驱动起来，
      // 可以通过Class.forName把它加载进去，也可以通过初始化来驱动起来，下面三种形式都可以
      Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动
      // or:
      // com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();
      // or：
      // new com.mysql.jdbc.Driver();

      System.out.println("成功加载MySQL驱动程序");
      // 一个Connection代表一个数据库连接
      conn = DriverManager.getConnection(jdbcUrl);
      // Statement里面带有很多方法，比如executeUpdate可以实现插入，更新和删除等
      String sql = "select node, table_name from " + dbName + "." + tbName + "_node order by node";
      statement = conn.createStatement();
      resultSet = statement.executeQuery(sql);
      while (resultSet.next()) {
        ret.put(resultSet.getLong(1), resultSet.getString(2).replaceAll(tbName, ""));
      }

    } catch (SQLException e) {
      System.out.println("MySQL操作错误");
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
    }

    return ret;
  }

  public static long getNodeKey(String id) {
    CRC32 crc32 = new CRC32();
    try {
      crc32.update(id.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      throw new UnsupportedCharsetException("Unsupported UTF-8 encoding.");
    }
    System.out.println(crc32.getValue());
    return crc32.getValue();
  }

  public static String getTableSuffix(Object object, TreeMap<Long, String> nodes) {
    String tableSuffix = null;

    long key = getNodeKey(object.toString());
    // 方法用来返回与该键至少大于或等于给定键，如果不存在这样的键的键 - 值映射，则返回null相关联。
    Entry<Long, String> node = nodes.ceilingEntry(key);
    if (node == null) {
      node = nodes.firstEntry();
    }
    tableSuffix = node.getValue();
    return tableSuffix;
  }

  public static void main(String[] args) {

    // public static final String host = "192.168.1.161";
    // public static final String user = "naliworld";
    // public static final String password = "password!";
    // public static final String dbName = "chaos";
    // public static final String tableName = "tb_comment";

    // public static final Long uid = 735l;
    TreeMap<Long, String> nodesTree = genNodes("192.168.1.161", "naliworld", "password!", "lamia", "tb_live_record_room");
    System.out.println(getTableSuffix(57543L, nodesTree));

  }

  public static String queryIbatorNode(String host, String user, String password, String dbName, String tbName,
      Long id) {

    TreeMap<Long, String> nodesTree = genNodes(host, user, password, dbName, tbName);
    String ret = getTableSuffix(id, nodesTree);
    return ret;
  }

}
